package two;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.net.URL;

/**
 * 对于无法处理的object，可以使用Tree Model 模式进行处理
 */
public class TreeModelExample {
    public static void main(String[] args) throws IOException {

        URL resource = TreeModelExample.class.getClassLoader().getResource("two/treemode.json");

        ObjectMapper mapper = new ObjectMapper();


        //解析成tree
        JsonNode root = mapper.readTree(resource);

        //读取节点，并按照约定的协议进行解析
        String name = root.get("name").asText();
        int age = root.get("age").asInt();
        System.out.format("%s:%d %n", name, age);


        //向节点中写入数据
        //写入对象
        ObjectNode other = root.with("properties");
        other.put("address", "Shanghai");
        other.put("phone", "123456");

        //写入数组
        ArrayNode arrayNode = root.withArray("hobbies");
        arrayNode.add("one");
        arrayNode.add("two");


        //查看节点
        System.out.println(mapper.writeValueAsString(root));

    }
}
